<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>智能控制中心 - 机器人状态</title>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  
  <!-- 配置Tailwind -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#0F172A',
            success: '#52C41A',
            warning: '#FAAD14',
            danger: '#FF4D4F',
            robot: {
              online: '#52C41A',
              offline: '#FF4D4F',
              idle: '#FAAD14',
              working: '#165DFF'
            }
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .sidebar-item-active {
        @apply bg-primary/10 text-primary border-l-4 border-primary;
      }
      .card-hover {
        @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
      }
      .robot-status-indicator {
        @apply w-3 h-3 rounded-full inline-block mr-2;
      }
      .fade-in {
        animation: fadeIn 0.5s ease-in-out;
      }
      .fade-out {
        animation: fadeOut 0.3s ease-in-out;
      }
      .scale-in {
        animation: scaleIn 0.3s ease-in-out;
      }
      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
      }
      @keyframes fadeOut {
        from { opacity: 1; transform: translateY(0); }
        to { opacity: 0; transform: translateY(10px); }
      }
      @keyframes scaleIn {
        from { opacity: 0; transform: scale(0.95); }
        to { opacity: 1; transform: scale(1); }
      }
    }
  </style>
</head>

<body class="font-inter bg-gray-50 text-gray-800 min-h-screen flex overflow-hidden">
  <!-- 左侧导航栏 -->
  <aside class="bg-white w-64 shadow-md z-10 hidden md:block transition-all duration-300 ease-in-out">
    <!-- 品牌标识 -->
    <div class="p-5 border-b border-gray-200">
      <div class="flex items-center space-x-3">
        <div class="w-10 h-10 rounded-lg bg-primary flex items-center justify-center">
          <i class="fa fa-cogs text-white text-xl"></i>
        </div>
        <h1 class="text-xl font-bold text-secondary">智能控制中心</h1>
      </div>
    </div>
    
    <!-- 导航菜单 -->
    <nav class="py-6 px-3">
      <p class="text-xs uppercase text-gray-500 font-semibold px-4 mb-3">控制功能</p>
      
      <a href="#elevator" class="flex items-center px-4 py-3 mb-1 rounded-md text-gray-600 hover:bg-gray-100 transition-colors cursor-pointer">
        <i class="fa fa-building-o w-6 text-center"></i>
        <span class="ml-3">电梯控制</span>
      </a>
      
      <a href="#gate" class="flex items-center px-4 py-3 mb-1 rounded-md text-gray-600 hover:bg-gray-100 transition-colors cursor-pointer">
        <i class="fa fa-sign-out w-6 text-center"></i>
        <span class="ml-3">闸机控制</span>
      </a>
      
      <a href="#robot" class="sidebar-item-active flex items-center px-4 py-3 mb-1 rounded-md cursor-pointer">
        <i class="fa fa-android w-6 text-center"></i>
        <span class="ml-3">机器人状态</span>
      </a>
      
      <div class="mt-8 pt-6 border-t border-gray-200">
        <p class="text-xs uppercase text-gray-500 font-semibold px-4 mb-3">系统</p>
        
        <a href="#settings" class="flex items-center px-4 py-3 mb-1 rounded-md text-gray-600 hover:bg-gray-100 transition-colors cursor-pointer">
          <i class="fa fa-cog w-6 text-center"></i>
          <span class="ml-3">设置</span>
        </a>
        
        <a href="#" class="flex items-center px-4 py-3 mb-1 rounded-md text-gray-600 hover:bg-gray-100 transition-colors cursor-pointer">
          <i class="fa fa-question-circle w-6 text-center"></i>
          <span class="ml-3">帮助中心</span>
        </a>
      </div>
    </nav>
  </aside>
  
  <!-- 主内容区域 -->
  <main class="flex-1 flex flex-col overflow-hidden">
    <!-- 顶部状态栏 -->
    <header class="bg-white shadow-sm px-6 py-4 flex justify-between items-center">
      <button class="md:hidden text-gray-500 focus:outline-none" id="menu-toggle">
        <i class="fa fa-bars text-xl"></i>
      </button>
      
      <div class="flex items-center space-x-6">
        <div class="relative">
          <input type="text" placeholder="搜索..." class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary w-64 transition-all">
          <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
        </div>
        
        <div class="flex items-center space-x-4">
          <button class="relative p-2 text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell text-xl"></i>
            <span class="absolute top-1 right-1 w-2 h-2 bg-danger rounded-full"></span>
          </button>
          
          <div class="flex items-center space-x-2">
            <img src="https://picsum.photos/id/1005/40/40" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
            <span class="hidden md:inline font-medium">管理员</span>
          </div>
        </div>
      </div>
    </header>
    
    <!-- 内容滚动区域 -->
    <div class="flex-1 overflow-y-auto p-6 bg-gray-50">
      <!-- 机器人状态页面 -->
      <section id="robot" class="mb-10">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-bold text-secondary">机器人状态</h2>
          <div class="text-sm text-gray-500">
            <span id="current-time-robot">2025-11-18 10:30:00</span>
          </div>
        </div>
        
        <!-- 操作按钮区 -->
        <div class="mb-6 flex justify-between items-center">
          <div>
            <p class="text-gray-600"><span id="onlineCount" class="font-medium text-robot-online">0</span> 台在线，<span id="totalCount" class="font-medium">0</span> 台总数</p>
          </div>
          <button id="addRobotBtn" class="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors flex items-center">
            <i class="fa fa-plus mr-2"></i> 添加机器人设备
          </button>
        </div>
        
        <!-- 机器人列表 -->
        <div id="robotsContainer" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <!-- 机器人将通过JSON数据动态加载 -->
        </div>
      </section>
    </div>
  </main>
  
  <!-- 配送任务模态框 -->
  <div id="deliveryModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-2xl scale-in">
      <div class="p-5 border-b border-gray-100 flex justify-between items-center">
        <h3 class="text-lg font-semibold">创建配送任务</h3>
        <button id="closeDeliveryModal" class="text-gray-500 hover:text-gray-700 transition-colors">
          <i class="fa fa-times text-xl"></i>
        </button>
      </div>
      <div class="p-5">
        <form id="deliveryForm" class="space-y-6">
          <input type="hidden" id="robotId" name="robotId">
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">机器人信息</label>
            <div class="bg-gray-50 p-3 rounded-lg">
              <p id="deliveryRobotName" class="font-medium"></p>
              <p id="deliveryRobotStatus" class="text-sm text-gray-500 mt-1"></p>
            </div>
          </div>
          
          <div>
            <label for="deliveryRoom" class="block text-sm font-medium text-gray-700 mb-1">目标房间</label>
            <select id="deliveryRoom" name="deliveryRoom" 
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                  required>
              <option value="">请选择房间</option>
              <option value="101">101 室</option>
              <option value="102">102 室</option>
              <option value="103">103 室</option>
              <option value="201">201 室</option>
              <option value="202">202 室</option>
              <option value="203">203 室</option>
              <option value="301">301 室</option>
              <option value="302">302 室</option>
              <option value="303">303 室</option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">物品选择</label>
            <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
              <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                <input type="checkbox" name="items" value="矿泉水" class="mr-2 text-primary">
                <span>矿泉水</span>
              </label>
              <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                <input type="checkbox" name="items" value="零食" class="mr-2 text-primary">
                <span>零食</span>
              </label>
              <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                <input type="checkbox" name="items" value="文件" class="mr-2 text-primary">
                <span>文件</span>
              </label>
              <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                <input type="checkbox" name="items" value="包裹" class="mr-2 text-primary">
                <span>包裹</span>
              </label>
              <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                <input type="checkbox" name="items" value="餐品" class="mr-2 text-primary">
                <span>餐品</span>
              </label>
              <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                <input type="checkbox" name="items" value="其他" class="mr-2 text-primary">
                <span>其他</span>
              </label>
            </div>
          </div>
          
          <div>
            <label for="deliveryNotes" class="block text-sm font-medium text-gray-700 mb-1">备注信息</label>
            <textarea id="deliveryNotes" name="deliveryNotes" rows="3" placeholder="请输入特殊要求或说明..."
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"></textarea>
          </div>
        </form>
      </div>
      <div class="p-5 border-t border-gray-100 flex justify-end space-x-3">
        <button id="cancelDeliveryBtn" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50 transition-colors">
          取消
        </button>
        <button id="confirmDeliveryBtn" class="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors">
          提交任务
        </button>
      </div>
    </div>
  </div>
  
  <!-- 添加机器人模态框 -->
  <div id="addRobotModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-md scale-in">
      <div class="p-5 border-b border-gray-100 flex justify-between items-center">
        <h3 class="text-lg font-semibold">添加机器人设备</h3>
        <button id="closeAddModalBtn" class="text-gray-500 hover:text-gray-700 transition-colors">
          <i class="fa fa-times text-xl"></i>
        </button>
      </div>
      <div class="p-5">
        <form id="addRobotForm" class="space-y-4">
          <div>
            <label for="robotName" class="block text-sm font-medium text-gray-700 mb-1">机器人名称</label>
            <input type="text" id="robotName" name="robotName" placeholder="例如：配送机器人 R-005" 
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                  required>
          </div>
          
          <div>
            <label for="robotType" class="block text-sm font-medium text-gray-700 mb-1">机器人类型</label>
            <select id="robotType" name="robotType" 
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                  required>
              <option value="">请选择类型</option>
              <option value="delivery">配送机器人</option>
              <option value="cleaning">清洁机器人</option>
              <option value="security">安防机器人</option>
              <option value="service">服务机器人</option>
            </select>
          </div>
          
          <div>
            <label for="robotId" class="block text-sm font-medium text-gray-700 mb-1">设备ID</label>
            <div class="flex">
              <input type="text" id="robotId" name="robotId" placeholder="例如：RB2025005" 
                    class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                    required>
              <button type="button" id="generateIdBtn" class="ml-2 px-3 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm hover:bg-gray-200 transition-colors">
                自动生成
              </button>
            </div>
          </div>
          
          <div>
            <label for="robotStatus" class="block text-sm font-medium text-gray-700 mb-1">初始状态</label>
            <select id="robotStatus" name="robotStatus" 
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                  required>
              <option value="online">在线</option>
              <option value="idle">空闲</option>
              <option value="offline">离线</option>
            </select>
          </div>
        </form>
      </div>
      <div class="p-5 border-t border-gray-100 flex justify-end space-x-3">
        <button id="cancelAddBtn" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50 transition-colors">
          取消
        </button>
        <button id="confirmAddBtn" class="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors">
          确认添加
        </button>
      </div>
    </div>
  </div>
  
  <!-- 移动端侧边栏遮罩 -->
  <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-20 hidden md:hidden"></div>
  
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // 机器人初始JSON数据
      const robotsData = [
        {
          id: "RB2025001",
          name: "配送机器人 R-001",
          type: "delivery",
          status: "online",
          currentStatus: "执行配送任务",
          battery: 78,
          taskProgress: 65,
          completedTasks: 0,
          lastOnline: null,
          error: null
        },
        {
          id: "RB2025002",
          name: "清洁机器人 R-002",
          type: "cleaning",
          status: "idle",
          currentStatus: "等待任务分配",
          battery: 92,
          taskProgress: 0,
          completedTasks: 5,
          lastOnline: null,
          error: null
        },
        {
          id: "RB2025003",
          name: "安防机器人 R-003",
          type: "security",
          status: "offline",
          currentStatus: "连接中断",
          battery: 35,
          taskProgress: 0,
          completedTasks: 0,
          lastOnline: "2025-11-18 08:45:12",
          error: "通讯模块异常"
        },
        {
          id: "RB2025004",
          name: "服务机器人 R-004",
          type: "service",
          status: "idle",
          currentStatus: "等待服务请求",
          battery: 85,
          taskProgress: 0,
          completedTasks: 3,
          lastOnline: null,
          error: null
        }
      ];
      
      // 元素引用
      const robotsContainer = document.getElementById('robotsContainer');
      const onlineCountEl = document.getElementById('onlineCount');
      const totalCountEl = document.getElementById('totalCount');
      const deliveryModal = document.getElementById('deliveryModal');
      const closeDeliveryModal = document.getElementById('closeDeliveryModal');
      const cancelDeliveryModal = document.getElementById('cancelDeliveryBtn');
      const confirmDeliveryBtn = document.getElementById('confirmDeliveryBtn');
      const deliveryRobotName = document.getElementById('deliveryRobotName');
      const deliveryRobotStatus = document.getElementById('deliveryRobotStatus');
      const robotIdInput = document.getElementById('robotId');
      
      // 添加机器人相关元素
      const addRobotBtn = document.getElementById('addRobotBtn');
      const addRobotModal = document.getElementById('addRobotModal');
      const closeAddModalBtn = document.getElementById('closeAddModalBtn');
      const cancelAddBtn = document.getElementById('cancelAddBtn');
      const confirmAddBtn = document.getElementById('confirmAddBtn');
      const generateIdBtn = document.getElementById('generateIdBtn');
      
      // 机器人计数器
      let robotCounter = 0;
      let onlineCounter = 0;
      
      // 机器人类型文本和图标映射
      const typeMap = {
        'delivery': { text: '配送机器人', icon: 'fa-truck' },
        'cleaning': { text: '清洁机器人', icon: 'fa-broom' },
        'security': { text: '安防机器人', icon: 'fa-shield' },
        'service': { text: '服务机器人', icon: 'fa-concierge-bell' }
      };
      
      // 状态样式映射
      const statusMap = {
        'online': { 
          class: 'robot-online',
          text: '在线',
          bgClass: 'bg-robot-online/10',
          textClass: 'text-robot-online',
          indicatorClass: 'bg-robot-online'
        },
        'idle': { 
          class: 'robot-idle',
          text: '空闲',
          bgClass: 'bg-robot-idle/10',
          textClass: 'text-robot-idle',
          indicatorClass: 'bg-robot-idle'
        },
        'offline': { 
          class: 'robot-offline',
          text: '离线',
          bgClass: 'bg-robot-offline/10',
          textClass: 'text-robot-offline',
          indicatorClass: 'bg-robot-offline'
        }
      };
      
      // 从JSON数据加载机器人
      function loadRobotsFromJson() {
        robotsContainer.innerHTML = '';
        robotCounter = 0;
        onlineCounter = 0;
        
        robotsData.forEach(robot => {
          // 创建机器人卡片
          const robotCard = createRobotCard(robot);
          robotsContainer.appendChild(robotCard);
          
          // 更新计数器
          robotCounter++;
          if (robot.status === 'online' || robot.status === 'idle') {
            onlineCounter++;
          }
        });
        
        // 更新显示的计数器
        onlineCountEl.textContent = onlineCounter;
        totalCountEl.textContent = robotCounter;
      }
      
      // 创建机器人卡片
      function createRobotCard(robot) {
        const statusConfig = statusMap[robot.status];
        let extraInfo = '';
        let actionBtn = '';
        
        // 根据机器人类型和状态设置额外信息
        if (robot.type === 'delivery' && robot.status === 'online') {
          extraInfo = `<div>
                        <h4 class="text-sm text-gray-500 mb-1">任务进度</h4>
                        <div class="flex items-center">
                          <div class="w-full bg-gray-200 rounded-full h-2.5 mr-2">
                            <div class="bg-primary h-2.5 rounded-full" style="width: ${robot.taskProgress}%"></div>
                          </div>
                          <span class="text-sm font-medium">${robot.taskProgress}%</span>
                        </div>
                      </div>`;
          actionBtn = '<i class="fa fa-cog mr-1"></i> 任务';
        } else if ((robot.type === 'cleaning' || robot.type === 'service') && 
                  (robot.status === 'online' || robot.status === 'idle')) {
          extraInfo = `<div>
                        <h4 class="text-sm text-gray-500 mb-1">今日完成</h4>
                        <p class="font-medium">${robot.completedTasks} 个任务</p>
                      </div>`;
          actionBtn = '<i class="fa fa-cog mr-1"></i> 任务';
        } else if (robot.status === 'offline') {
          extraInfo = `<div>
                        <h4 class="text-sm text-gray-500 mb-1">最后在线</h4>
                        <p class="font-medium">${robot.lastOnline}</p>
                      </div>
                      <div>
                        <h4 class="text-sm text-gray-500 mb-1">故障提示</h4>
                        <p class="font-medium text-danger">${robot.error}</p>
                      </div>`;
          actionBtn = '<i class="fa fa-refresh mr-1"></i> 重连';
        }
        
        // 创建卡片元素
        const card = document.createElement('div');
        card.className = 'bg-white rounded-xl shadow-sm overflow-hidden card-hover fade-in';
        card.dataset.robotId = robot.id;
        card.dataset.status = robot.status;
        card.dataset.type = robot.type;
        card.innerHTML = `
          <div class="p-5 border-b border-gray-100">
            <div class="flex justify-between items-start">
              <div class="flex items-center">
                <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center mr-3">
                  <i class="fa ${typeMap[robot.type].icon} text-primary text-xl"></i>
                </div>
                <div>
                  <h3 class="font-semibold">${robot.name}</h3>
                  <p class="text-sm text-gray-500">ID: ${robot.id}</p>
                </div>
              </div>
              <span class="px-2 py-1 ${statusConfig.bgClass} ${statusConfig.textClass} text-xs rounded-full">
                <span class="robot-status-indicator ${statusConfig.indicatorClass}"></span>${statusConfig.text}
              </span>
            </div>
          </div>
          <div class="p-5">
            <div class="space-y-4">
              <div>
                <h4 class="text-sm text-gray-500 mb-1">当前状态</h4>
                <p class="font-medium ${robot.status === 'offline' ? 'text-danger' : ''}">${robot.currentStatus}</p>
              </div>
              <div>
                <h4 class="text-sm text-gray-500 mb-1">电池电量</h4>
                <div class="flex items-center">
                  <div class="w-full bg-gray-200 rounded-full h-2.5 mr-2">
                    <div class="bg-robot-working h-2.5 rounded-full" style="width: ${robot.battery}%"></div>
                  </div>
                  <span class="text-sm font-medium">${robot.battery}%</span>
                </div>
              </div>
              ${extraInfo}
            </div>
            
            <div class="mt-5 flex justify-end space-x-2">
              <button class="delete-robot-btn px-3 py-1.5 border border-danger text-danger rounded-lg text-sm hover:bg-danger/10 transition-colors">
                <i class="fa fa-trash mr-1"></i> 删除
              </button>
              <button class="px-3 py-1.5 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50 transition-colors">
                <i class="fa fa-history mr-1"></i> 历史
              </button>
              <button class="task-robot-btn px-3 py-1.5 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors ${robot.status === 'offline' ? 'opacity-50 cursor-not-allowed' : ''}">
                ${actionBtn}
              </button>
            </div>
          </div>
        `;
        
        // 绑定任务按钮事件
        const taskBtn = card.querySelector('.task-robot-btn');
        if (robot.status !== 'offline') {
          taskBtn.addEventListener('click', () => openDeliveryModal(robot));
        }
        
        // 绑定删除按钮事件
        const deleteBtn = card.querySelector('.delete-robot-btn');
        deleteBtn.addEventListener('click', function() {
          if (confirm(`确定要删除 ${robot.name} 吗？`)) {
            card.classList.add('fade-out');
            setTimeout(() => {
              card.remove();
              updateRobotCounters();
              // 从数据中移除
              const index = robotsData.findIndex(r => r.id === robot.id);
              if (index !== -1) {
                robotsData.splice(index, 1);
              }
            }, 300);
          }
        });
        
        return card;
      }
      
      // 打开配送任务模态框
      function openDeliveryModal(robot) {
        deliveryRobotName.textContent = robot.name;
        deliveryRobotStatus.textContent = `状态: ${statusMap[robot.status].text} | 电池: ${robot.battery}%`;
        robotIdInput.value = robot.id;
        document.getElementById('deliveryForm').reset();
        deliveryModal.classList.remove('hidden');
      }
      
      // 关闭配送任务模态框
      function closeDeliveryModalFunc() {
        deliveryModal.classList.add('hidden');
      }
      
      // 提交配送任务
      confirmDeliveryBtn.addEventListener('click', () => {
        const robotId = robotIdInput.value;
        const room = document.getElementById('deliveryRoom').value;
        const selectedItems = Array.from(document.querySelectorAll('input[name="items"]:checked')).map(el => el.value);
        
        if (!room) {
          alert('请选择目标房间');
          return;
        }
        
        if (selectedItems.length === 0) {
          alert('请至少选择一种物品');
          return;
        }
        
        // 更新机器人状态
        const robot = robotsData.find(r => r.id === robotId);
        if (robot) {
          robot.status = 'online';
          robot.currentStatus = `配送至 ${room} 室`;
          robot.taskProgress = 30;
          
          const robotCard = document.querySelector(`[data-robot-id="${robotId}"]`);
          if (robotCard) {
            const newCard = createRobotCard(robot);
            robotCard.parentNode.replaceChild(newCard, robotCard);
          }
        }
        
        showNotification(`已成功为 ${deliveryRobotName.textContent} 创建配送任务`, 'success');
        closeDeliveryModalFunc();
      });
      
      // 添加机器人相关功能
      addRobotBtn.addEventListener('click', () => {
        addRobotModal.classList.remove('hidden');
        document.getElementById('addRobotForm').reset();
      });
      
      // 关闭添加机器人模态框
      function closeAddModal() {
        addRobotModal.classList.add('hidden');
      }
      
      closeAddModalBtn.addEventListener('click', closeAddModal);
      cancelAddBtn.addEventListener('click', closeAddModal);
      
      // 点击模态框外部关闭
      addRobotModal.addEventListener('click', (e) => {
        if (e.target === addRobotModal) {
          closeAddModal();
        }
      });
      
      // 自动生成机器人ID
      generateIdBtn.addEventListener('click', () => {
        const robotIdInput = document.getElementById('robotId');
        const year = new Date().getFullYear();
        const newId = `RB${year}${(robotCounter + 1).toString().padStart(3, '0')}`;
        robotIdInput.value = newId;
      });
      
      // 确认添加机器人
      confirmAddBtn.addEventListener('click', () => {
        const robotName = document.getElementById('robotName').value;
        const robotType = document.getElementById('robotType').value;
        const robotId = document.getElementById('robotId').value;
        const robotStatus = document.getElementById('robotStatus').value;
        
        if (!robotName || !robotType || !robotId || !robotStatus) {
          alert('请填写完整的机器人信息');
          return;
        }
        
        // 检查ID是否已存在
        const idExists = robotsData.some(r => r.id === robotId);
        if (idExists) {
          alert('该设备ID已存在，请使用其他ID');
          return;
        }
        
        // 生成新机器人数据
        let batteryLevel, currentStatus, taskProgress, completedTasks, lastOnline, error;
        
        if (robotStatus === 'online') {
          batteryLevel = Math.floor(Math.random() * 30) + 70;
          currentStatus = '执行任务中';
          taskProgress = Math.floor(Math.random() * 70) + 10;
          completedTasks = Math.floor(Math.random() * 5) + 1;
          lastOnline = null;
          error = null;
        } else if (robotStatus === 'idle') {
          batteryLevel = Math.floor(Math.random() * 30) + 70;
          currentStatus = '等待任务分配';
          taskProgress = 0;
          completedTasks = Math.floor(Math.random() * 5) + 1;
          lastOnline = null;
          error = null;
        } else { // offline
          batteryLevel = Math.floor(Math.random() * 40) + 10;
          currentStatus = '连接中断';
          taskProgress = 0;
          completedTasks = 0;
          lastOnline = new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(',', '');
          error = '通讯模块异常';
        }
        
        // 创建新机器人对象
        const newRobot = {
          id: robotId,
          name: robotName,
          type: robotType,
          status: robotStatus,
          currentStatus: currentStatus,
          battery: batteryLevel,
          taskProgress: taskProgress,
          completedTasks: completedTasks,
          lastOnline: lastOnline,
          error: error
        };
        
        // 添加到数据数组
        robotsData.push(newRobot);
        
        // 创建并添加卡片
        const newRobotCard = createRobotCard(newRobot);
        robotsContainer.appendChild(newRobotCard);
        
        // 更新计数器
        robotCounter++;
        if (robotStatus === 'online' || robotStatus === 'idle') {
          onlineCounter++;
        }
        
        onlineCountEl.textContent = onlineCounter;
        totalCountEl.textContent = robotCounter;
        
        showNotification('机器人添加成功！', 'success');
        closeAddModal();
      });
      
      // 更新机器人计数器
      function updateRobotCounters() {
        const allRobots = document.querySelectorAll('#robotsContainer > div');
        const onlineRobots = Array.from(allRobots).filter(robot => {
          const status = robot.dataset.status;
          return status === 'online' || status === 'idle';
        });
        
        robotCounter = allRobots.length;
        onlineCounter = onlineRobots.length;
        
        onlineCountEl.textContent = onlineCounter;
        totalCountEl.textContent = robotCounter;
      }
      
      // 显示通知提示
      function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        const bgColors = {
          success: 'bg-success',
          info: 'bg-primary',
          error: 'bg-danger'
        };
        
        notification.className = `fixed top-4 right-4 ${bgColors[type]} text-white px-4 py-2 rounded-lg shadow-lg z-50 fade-in`;
        notification.textContent = message;
        document.body.appendChild(notification);
        
        setTimeout(() => {
          notification.style.opacity = '0';
          notification.style.transform = 'translateY(-10px)';
          notification.style.transition = 'opacity 0.3s, transform 0.3s';
          setTimeout(() => notification.remove(), 300);
        }, 3000);
      }
      
      // 绑定事件
      closeDeliveryModal.addEventListener('click', closeDeliveryModalFunc);
      cancelDeliveryModal.addEventListener('click', closeDeliveryModalFunc);
      
      deliveryModal.addEventListener('click', (e) => {
        if (e.target === deliveryModal) {
          closeDeliveryModalFunc();
        }
      });
      
      // 更新当前时间
      function updateTime() {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(',', '');
        
        document.getElementById('current-time-robot').textContent = timeString;
      }
      
      // 导航菜单切换逻辑
      const menuToggle = document.getElementById('menu-toggle');
      const sidebar = document.querySelector('aside');
      const sidebarOverlay = document.getElementById('sidebar-overlay');
      
      menuToggle.addEventListener('click', () => {
        sidebar.classList.toggle('hidden');
        sidebar.classList.toggle('absolute');
        sidebar.classList.toggle('top-0');
        sidebar.classList.toggle('left-0');
        sidebar.classList.toggle('h-full');
        sidebarOverlay.classList.toggle('hidden');
      });
      
      sidebarOverlay.addEventListener('click', () => {
        sidebar.classList.add('hidden');
        sidebarOverlay.classList.add('hidden');
      });
      
      // 初始化
      loadRobotsFromJson();
      updateTime();
      setInterval(updateTime, 1000);
    });
  </script>
</body>
</html>
